import { bridgeOpenApi } from './bridge';

export interface UserInfo {
  loginId: string
  maturity: number
  trustScore: number
  userId: number
  createDate: number
  rateNum: number
  categoryId: number
  tpYear: number
  rateSum: number
  memberId: string
  shopUrl: string
  icon: string
  phoneNo: string
  product: string
  addressLocation: string
  sellerName: string
  pm: boolean
  fm: boolean
  isOfficalLogistics: boolean
  openUid: string
}

export interface AuthResponse {
  success: boolean
  result: {
    requestId: string
    code: string
    message: string
    data: {
      result: UserInfo
      success: boolean
    }
  }
}

// 方案一：调用 mtop.1688.authorization.plugin.refresh，返回体里包含 memberId（如 b2b-xxxxxxxx）
export async function fetchMemberIdViaMtop(): Promise<UserInfo | undefined> {
  // 简化为仅使用基础账号接口，避免网关版本形态差异带来的 ParamMissing
  const basic = await fetchAccountBasic();
  console.log("🚀 ~ fetchMemberIdViaMtop ~ basic:", basic)
  const user = basic?.result?.data?.result
  // 优先 memberId；退化为 openUid/userId 以满足后续登录
  return user
}

// 方案二：老接口，获取基础账号信息（可能拿到 userId，但不一定有 memberId）
export async function fetchAccountBasic(): Promise<AuthResponse> {
  const res: AuthResponse = await bridgeOpenApi({
    version: '1',
    namespace: 'com.alibaba.account',
    name: 'alibaba.account.basic',
    data: {},
  });
  return res;
}

// 工具函数：将相对路径转换为完整URL
export function toAliImageUrl(icon?: string): string {
  if (!icon) return '';
  if (/^https?:\/\//.test(icon)) return icon;      // 已是完整 URL
  if (icon.startsWith('//')) return `https:${icon}`; // 协议相对
  return `https://cbu01.alicdn.com${icon.startsWith('/') ? '' : '/'}${icon}`;
}


